package com.manage.service;

import com.manage.service.ICallback;
import com.manage.service.IService;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

public class AppService extends Service {

	private static final String TAG = "AppService";

	private RemoteCallbackList<ICallback> mCallbacks = new RemoteCallbackList<ICallback>();

	private IService.Stub mBinder = new IService.Stub() {

		@Override
		public void unregisterCallback(ICallback cb) {
			if (cb != null) {
				mCallbacks.unregister(cb);
			}
		}

		@Override
		public void registerCallback(ICallback cb) {
			if (cb != null) {
				mCallbacks.register(cb);
			}
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
	
	private void callBack() {
        int N = mCallbacks.beginBroadcast();
        try {
            for (int i = 0; i < N; i++) {
                mCallbacks.getBroadcastItem(i).refresh();
            }
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
        mCallbacks.finishBroadcast();
    }
	
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            callBack();
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        //这里不知道为什么,直接使用callback方法回调showResult
        //mCallbacks.beginBroadcast()是0,需要用handler延迟1000毫秒
        //也许是在activity中binService太耗时的原因?
        mHandler.sendEmptyMessageDelayed(0, 1000);
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        mHandler.removeMessages(0);
        mCallbacks.kill();
        super.onDestroy();
    }

}
